package com.taiyuan.tongcheng.ui;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.kymjs.kjframe.KJHttp;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.http.HttpConfig;
import org.kymjs.kjframe.http.HttpParams;
import org.kymjs.kjframe.ui.BindView;
import org.kymjs.kjframe.utils.KJLoger;
import org.kymjs.kjframe.utils.StringUtils;
import org.kymjs.kjframe.utils.SystemTool;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.taiyuan.tongcheng.adapter.MoneyCardAdapter;
import com.taiyuan.tongcheng.application.TCBroadcastAction;
import com.taiyuan.tongcheng.bean.MoneyCardDto;
import com.taiyuan.tongcheng.bean.PageInfo;
import com.taiyuan.tongcheng.bean.ZcOrderInfo;
import com.taiyuan.tongcheng.http.HttpParamUtil;
import com.taiyuan.tongcheng.http.TcWebservice;
import com.taiyuan.tongcheng.http.WebData;
import com.taiyuan.tongcheng.jsonparser.TcJsParser;
import com.taiyuan.tongcheng.widget.EmptyLayout;
import com.taiyuan.tongcheng.widget.listview.FooterLoadingLayout;
import com.taiyuan.tongcheng.widget.listview.PullToRefreshBase;
import com.taiyuan.tongcheng.widget.listview.PullToRefreshList;
import com.taiyuan.tongcheng.widget.listview.PullToRefreshBase.OnRefreshListener;
import com.tytc56.user.R;

/**
 * 
* @Description 优惠券列表集合
* @author Administrator  
* @date 2015年9月16日 上午1:39:54 
* @update (date)
* @version V1.0
 */
public class CardListActivity extends BaseActivity implements OnItemClickListener{
//	widget
	@BindView(id=R.id.btn_cardno_duihuan,click=true)
	private Button duihuanBtn;
	@BindView(id=R.id.btn_no_use_card,click=true)
	private Button unuseBtn;
	@BindView(id=R.id.etv_card_code)
	private EditText cardCodeEtv;
	@BindView(id = R.id.empty_layout)
	private EmptyLayout mEmptyLayout;
	@BindView(id = R.id.pull_list_coupon)
	private PullToRefreshList mRefreshLayout;
	private ListView moneyCardLV;
	@BindView(id=R.id.rl_duihuan_moneycode)
	private RelativeLayout  duihuanLayout;
	@BindView(id=R.id.ll_nocoupon)
	private LinearLayout  nocouponLayout;
   //数据
	private List<MoneyCardDto>  moneyCardList =new ArrayList<MoneyCardDto>() ;
    private PageInfo pageInfo;
    private MoneyCardAdapter  moneyCardAdapter;
    private List<String > moneyCardString =new ArrayList<String>();
    private int tcPage;
    //跳转
    private int COMFLAG_USER  =0;
    private int COMFLAG_ORDER =1;
    private int comFlag;
    
    public static  String TAG_MONEY_CARD_FROM ="TAG_MONEY_CARD_FROM";
    public static  String TAG_CARD_NO ="TAG_CARD_NO";
    public static  String TAG_CARD_PRICE ="TAG_CARD_PRICE";
    
	@Override
	public void setRootView() {
		setContentView(R.layout.activity_money_card);
	}
	
	@Override
	protected void initView() {
		super.initView();
	}
	
	@Override
	public void initWidget() {
		super.initWidget();
		initView();
		listViewPreference();
		comFlag = getIntent().getIntExtra(TAG_MONEY_CARD_FROM, 0);
		KJLoger.debug("comfalg"+comFlag);
		if(comFlag==COMFLAG_ORDER){
			moneyCardLV.setOnItemClickListener(this);
		}else{
//			duihuanLayout.setVisibility(View.GONE);
			unuseBtn.setVisibility(View.GONE);
		}
		topTv.setText(R.string.user_coupon);
		rightTv.setVisibility(View.GONE);
		//========testconpon============
//		cardCodeEtv.setText("B9YKZGR9CLUMKE220150919204926");
		moneyCardAdapter=new MoneyCardAdapter(getApplicationContext(),moneyCardList);
		moneyCardLV.setAdapter(moneyCardAdapter);
		mEmptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
                refresh();
            }
        });
	}
	
	@Override
	public void widgetClick(View v) {
		super.widgetClick(v);
		switch (v.getId()) {
		case R.id.btn_cardno_duihuan:
			if(checkNull()){
				duihuanCard(cardCodeEtv.getText().toString().trim());
			}
			break;
	     case R.id.btn_no_use_card:
	    	getIntent().putExtra(TAG_CARD_NO, "no");
			setResult(RESULT_OK, getIntent());
			this.finish();
			break;
		default:
			break;
		}
	}
	
	
	private boolean checkNull() {
		if(StringUtils.isEmpty(cardCodeEtv.getText())){
			showErroCustomToast("请输入兑换编号");
			return false;
		}
		
		if(!SystemTool.checkNet(getApplicationContext())){
			return false;
		}
		return true;
	}

	/**
	  * 
	 * @Description: 初始话样式
	 * @return void
	 * @throws
	 * @autour Administrator
	 * @date 2015-8-30 下午12:37:39 
	 * @update (date)
	  */
   @SuppressLint("NewApi")
	private void listViewPreference() {
       moneyCardLV = mRefreshLayout.getRefreshView();
       moneyCardLV.setDivider(new ColorDrawable(android.R.color.transparent));
       moneyCardLV.setSelector(new ColorDrawable(android.R.color.transparent));
       moneyCardLV.setOverscrollFooter(null);
       moneyCardLV.setOverscrollHeader(null);
       moneyCardLV.setOverScrollMode(ListView.OVER_SCROLL_NEVER);
       mRefreshLayout.setPullLoadEnabled(true);
       ((FooterLoadingLayout) mRefreshLayout.getFooterLoadingLayout())
               .setNoMoreDataText("没有更多的数据了");
      
       moneyCardLV.setOnItemClickListener(new OnItemClickListener() {
           @Override
           public void onItemClick(AdapterView<?> parent, View view,
                   int position, long id) {
        	   
           }
       });
       
       mRefreshLayout.setOnRefreshListener(new OnRefreshListener<ListView>() {
           @Override
           public void onPullDownToRefresh(
                   PullToRefreshBase<ListView> refreshView) {
           	fillOrderData();
           }

           @Override
           public void onPullUpToRefresh(
               PullToRefreshBase<ListView> refreshView) {
               refresh();
           }
       });
       fillOrderData();
   }
	
   private void fillOrderData() {
   	tcPage=1;
   	getMoneyCarList(1,0,0);
   }

   private void refresh() {
	   getMoneyCarList(tcPage,0,0);
   }
	
	/**
	 * 
	* @Description: 获取优惠券集合
	* @return void
	* @throws
	* @autour Administrator
	* @date 2015年9月16日 上午1:48:33 
	* @update (date)
	 */
	private void getMoneyCarList (final int pageIndex,int usedFlag,int expireFlag) {
		HttpConfig config =new HttpConfig();
		config.cacheTime=0;
		KJHttp kjHttp =new KJHttp(config);
		HttpParams params= HttpParamUtil.GetCardListParams(this, pageIndex, usedFlag, expireFlag, "desc");
		KJLoger.debug(params.getUrlParams().toString());
		kjHttp.post(TcWebservice.WEBSERVER_IP+TcWebservice.API.GET_CARDLIST, params, new HttpCallBack() {

			@Override
			public void onFailure(int errorNo, String strMsg) {
				super.onFailure(errorNo, strMsg);
				showErroCustomToast("获取优惠券失败");
			}

			@Override
			public void onSuccess(String t) {
				super.onSuccess(t);
				try {
					String response = URLDecoder.decode(t,"UTF-8");
					KJLoger.debug(response);
					WebData  data =new WebData();
					data=TcJsParser.getWedataData(response);
					if(data.getStatus()==1){
						List<MoneyCardDto > cardRecList=new ArrayList<MoneyCardDto>();
						cardRecList.clear();
						com.alibaba.fastjson.JSONObject cardListJson =JSON.parseObject(data.getData());  
						pageInfo = JSON.parseObject( cardListJson.getString("pageInfo"), PageInfo.class);
//						KJLoger.debug(pageInfo.toString());
						//解析搬家订单
						moneyCardString=JSON.parseArray(cardListJson.getString("dataList"), String.class);
						if(moneyCardString.size()==0){
							showErroCustomToast("无优惠卷可用");
							nocouponLayout.setVisibility(View.VISIBLE);
						}else{
							nocouponLayout.setVisibility(View.GONE);
						}
						
						for (String jsonString : moneyCardString) {
							MoneyCardDto info = JSON.parseObject(jsonString,MoneyCardDto.class);
							cardRecList.add(info);
						}
						KJLoger.debug(cardRecList.size()+"jihe");
						
						if(pageIndex==1){
							moneyCardList.clear();
							moneyCardList.addAll(cardRecList);
						}else{
							moneyCardList.addAll(cardRecList);
						}
						  tcPage++;
						  KJLoger.debug("list-size="+moneyCardList.size()+"=tcpage="+tcPage);
						  moneyCardAdapter.notifyDataSetChanged();
						 mEmptyLayout.dismiss();
						KJLoger.debug(moneyCardList.toString());
						
					}else if(data.getStatus()==0){
						showErroCustomToast("获取参数失败");
					}else if(data.getStatus()==-1){
						showErroCustomToast(data.getMsg());
						GotoLogin();
					}
					
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
			
			@Override
    		public void onFinish() {
    			super.onFinish();
    			//关闭上拉、下拉刷写
    	         mRefreshLayout.onPullDownRefreshComplete();
                 mRefreshLayout.onPullUpRefreshComplete();
    		}
		
		});
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		moneyCardAdapter.setSlectPosition(position);
		moneyCardAdapter.notifyDataSetChanged();
		getIntent().putExtra(TAG_CARD_NO, moneyCardList.get(position).getCode());
		getIntent().putExtra(TAG_CARD_PRICE, moneyCardList.get(position).getMoney());
		KJLoger.debug(moneyCardList.get(position).getCode());
		setResult(RESULT_OK, getIntent());
		CardListActivity.this.finish();
	}
	
	/**
	 * 
	* @Description: 兑换优惠劵
	* @param cardNo
	* @return void
	* @throws
	* @autour wzq
	* @date 2015-9-21 下午6:16:47
	* @update (date)
	 */
	private void duihuanCard(String cardNo) {
        TcLoaddingDialog.show();
		HttpConfig config = new HttpConfig();
		config.cacheTime = 0;
		KJHttp kjHttp = new KJHttp(config);
		HttpParams params = HttpParamUtil.getDuihuanCouponParam(
				getApplicationContext(), cardNo);
		kjHttp.post(TcWebservice.WEBSERVER_IP + TcWebservice.API.UBIND_COUPON,
				params, new HttpCallBack() {

					@Override
					public void onFailure(int errorNo, String strMsg) {
						super.onFailure(errorNo, strMsg);
						showErroCustomToast("兑换失败");
					}

					@Override
					public void onSuccess(String t) {
						super.onSuccess(t);
						try {
							String response = URLDecoder.decode(t, "UTF-8");
							KJLoger.debug(response);
							WebData data = new WebData();
							data = TcJsParser.getWedataData(response);
							if (data.getStatus() == 1) {
								showSingleDialog("提示", "恭喜你，优惠券兑换成功", new View.OnClickListener() {
									
									@Override
									public void onClick(View v) {
										fillOrderData();
										tcInformDialog.dismiss();
									}
								});
							} else if (data.getStatus() == 0) {
								showErroCustomToast(data.getMsg());
							}else if(data.getStatus()==-1){
								showErroCustomToast(data.getMsg());
								GotoLogin();
							}
							if(TcLoaddingDialog.isShowing()){
								TcLoaddingDialog.dismiss();
							}

						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFinish() {
						super.onFinish();
					}

				});

	}	
	
}
